package com.yuju.login.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.weixin.mp.api.WxMpServiceImpl;
import com.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import com.weixin.mp.bean.result.WxMpUser;
import com.yuju.cache.RedisCache;
import com.yuju.common.core.dao.IBaseDao;
import com.yuju.common.core.service.AbstractBaseService;
import com.yuju.config.Config;
import com.yuju.constant.CacheKey;
import com.yuju.enums.RegisterReturnCodeEnum;
import com.yuju.enums.StatusEnum;
import com.yuju.exception.BusinessException;
import com.yuju.group.model.GroupModel;
import com.yuju.group.model.MemberLevelModel;
import com.yuju.group.model.MemberModel;
import com.yuju.group.service.IGroupService;
import com.yuju.group.service.IMemberLevelService;
import com.yuju.group.service.IMemberService;
import com.yuju.login.dao.entity.Op;
import com.yuju.login.model.OpModel;
import com.yuju.login.service.IOpService;
import com.yuju.login.service.IRegisterService;
import com.yuju.util.Utils;
/**
 * 
 * 类名：RegisterServiceImpl  <br />
 *
 * 功能：注册
 *
 * @author : zhousc <br />
 * @Date : 2018年1月5日 下午2:45:34  <br />
 * @version : 1.1 <br />
 */
@Service
public class RegisterServiceImpl extends AbstractBaseService<OpModel, Op, String> implements IRegisterService{

	@Autowired
	private IOpService opService;
	@Autowired
	private IMemberService memberService;
	@Autowired
	private IMemberLevelService memberLevelService;
	@Autowired
	private IGroupService groupService;
	
	
	@Override
	public IBaseDao<OpModel, Op, String> getDao() {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 
	 * 功能:微信注册 <br/>
	 * 
	 * 重写：zhousc <br/>
	 * 
	 * @Date ：2018年1月5日 下午3:03:51<br/>
	 * 
	 * @param opModel
	 * @return <br/>
	 * @throws Exception 
	 * @see com.yuju.login.service.IRegisterService#register(com.yuju.login.model.OpModel)
	 */
	@Override
	public int register(OpModel opModel) throws Exception {
		//根据手机号验证验证码
		RedisCache simpleCache = RedisCache.getInstance();
		String cacheVerCode = (String) simpleCache.get(opModel.getMobile() + CacheKey.KEY_CACHE_REGISTER_VERIFY_CODE);

		//如果验证码失效，抛出失效异常信息
		if(Utils.isNull(simpleCache)){
			throw new BusinessException(RegisterReturnCodeEnum.CODE_FAILURE.getCode()
					, RegisterReturnCodeEnum.CODE_FAILURE.getDesc());
		}
		//判断验证码是否正确，错误则抛出 ，验证码错误异常
		if(!opModel.getVerificationCode().equals(cacheVerCode) ){
			throw new BusinessException(RegisterReturnCodeEnum.CODE_VAILD_FAILURE.getCode()
					, RegisterReturnCodeEnum.CODE_VAILD_FAILURE.getDesc());
		}
//		//验证此openID是否已经注册
//		OpModel m = new OpModel();
//		m.setOpenId(opModel.getOpenId());
//		List<OpModel> list = opService.list(opModel);
//		if(list.size() > 0){
//			throw new BusinessException(RegisterReturnCodeEnum.ID_REPEAT.getCode()
//					, RegisterReturnCodeEnum.ID_REPEAT.getDesc());
//		}
		//验证此手机号是否已经注册
		OpModel selectByMobile = new OpModel();
		selectByMobile.setName(opModel.getMobile());
		List<OpModel> selectByMobileList = opService.list(selectByMobile);
		if(selectByMobileList.size() > 0){
			throw new BusinessException(RegisterReturnCodeEnum.ID_REPEAT.getCode()
					, RegisterReturnCodeEnum.ID_REPEAT.getDesc());
		}
		
		//根据前端传来的grpCode 查询对应集团的ID
		GroupModel groupModel = new GroupModel();
		groupModel.setCode(opModel.getGrpCode());
		GroupModel group = groupService.find(groupModel);
		
		//验证码正确，执行新增账号操作
		WxMpServiceImpl service = Config.getWxMpServiceImpl(group.getId());
		if (opModel.getCode() != null && !opModel.getCode().equals("")) {
			WxMpOAuth2AccessToken accessToken;
				accessToken = service.oauth2getAccessToken(opModel.getCode());
			if (accessToken != null) {
//				// 获取用户基本信息
				WxMpUser wxMpUser = service.oauth2getUserInfo(accessToken, null);
				System.out.println(wxMpUser.toString());
//				//微信openId
				String openId = wxMpUser.getOpenId();
//				//用户微信名
				String nickname = new String(wxMpUser.getNickname().getBytes("ISO-8859-1"), "UTF-8");
				
				saveMemberInfo(group, opModel, nickname, openId);
//				
				/*OpModel model = new OpModel();
				model.setOpenId(openId);
				model.setWxName(nickname);
				//用户手机号作为账号
				model.setName(opModel.getMobile());
				model.setPassword(opModel.getPassword());
				//根据前端传来的grpCode 查询对应集团的ID
				GroupModel groupModel = new GroupModel();
				groupModel.setCode(opModel.getGrpCode());
				GroupModel find = groupService.find(groupModel);
				model.setGroupId(find.getId());
				
				opService.wxGuestSave(model);
				//根据groupId查询对应的微信会员级别ID
				MemberLevelModel memberLevelModel = new MemberLevelModel();
				memberLevelModel.setGroupId(opModel.getGroupId());
				memberLevelModel.setName("微信会员");
				MemberLevelModel levelModel = memberLevelService.find(memberLevelModel);
				//新增会员信息
				MemberModel memberModel = new MemberModel();
				if(Utils.isNotNull(levelModel)){
					memberModel.setMemberLevelId(levelModel.getId());
				}
				memberModel.setName(nickname);
//				memberModel.setName(opModel.getMobile());
				memberModel.setPhone(opModel.getMobile());
				memberModel.setGroupId(find.getId());
				memberService.save(memberModel);*/
			}
		} else {
			//saveMemberInfo(opModel, null, null);
			throw new BusinessException(RegisterReturnCodeEnum.WX_CODE_NOT_NULL.getCode(),
					RegisterReturnCodeEnum.WX_CODE_NOT_NULL.getDesc());
		}
		return 1;
	}
	
	private void saveMemberInfo(GroupModel group, OpModel opModel, String nickname, String openId) {
		try {
		OpModel model = new OpModel();
		if (null != openId) {
			model.setOpenId(openId);
			model.setWxName(nickname);
		}
		//用户手机号作为账号
		model.setName(opModel.getMobile());
		model.setPassword(opModel.getPassword());
		/*//根据前端传来的grpCode 查询对应集团的ID
		GroupModel groupModel = new GroupModel();
		groupModel.setCode(opModel.getGrpCode());
		GroupModel find = groupService.find(groupModel);*/
		model.setGroupId(group.getId());
		model.setId(Utils.getUUID());
		model.setStatus(StatusEnum.TRUE.getValue());
		
		// opService.saveWxGuest(model);
		//根据groupId查询对应的微信会员级别ID
		MemberLevelModel memberLevelModel = new MemberLevelModel();
		memberLevelModel.setGroupId(group.getId());
		memberLevelModel.setName("微信会员");
		MemberLevelModel levelModel = memberLevelService.find(memberLevelModel);
		//新增会员信息
		MemberModel memberModel = new MemberModel();
		if(Utils.isNotNull(levelModel)){
			memberModel.setMemberLevelId(levelModel.getId());
		}
		if (null != openId) {
			memberModel.setName(nickname);
		} else {
			memberModel.setName("微信会员");
		}
//		memberModel.setName(opModel.getMobile());
		memberModel.setPhone(opModel.getMobile());
		memberModel.setGroupId(group.getId());
		String memberId = memberService.saveMember(memberModel);
		
		/*OpModel updateModel = new OpModel();
		updateModel.setId(model.getId());
		updateModel.setUserId(memberId);
		opModel.setUserName(memberModel.getName());
		opService.updateOp(updateModel);*/
		model.setUserId(memberId);
		opService.saveWxGuest(model);
		} catch(Exception e) {
			e.printStackTrace();
			throw new BusinessException("yuju-0000", e.getMessage());
		}
	}
}
